<?php
/**
 * Controller that allows users modification.
 * 
 * @version $Id: UserController.php,v 1.3 2011-06-17 04:43:21 herve Exp $
 * @copyright 2011
 */
class UserController extends CController {

	const PAGE_SIZE = 10;

	public function getSubmenu()
	{
		$all = array();
		if(Yii::app()->user->checkAccess('Users.canCreate'))
		{
			$all['create'] = array(
					'icon' => Yii::app()->request->baseUrl . '/images/add.png',
					'label' => Yii::t('submenu', 'New user'),
					'href' => array('create')
				);
		}

		if(Yii::app()->user->checkAccess('Users.canList'))
		{
			$all['admin'] = array(
					'icon' => Yii::app()->request->baseUrl . '/images/list.png',
					'label' => Yii::t('submenu', 'Manage users'),
					'href' => array('admin')
				);
		}
		
		if ($this->_model != null) {
			if(Yii::app()->user->checkAccess('Users.canUpdate'))
			{
				$all['update'] = array(
						'icon' => Yii::app()->request->baseUrl . '/images/edit.png',
						'label' => Yii::t('submenu', 'Update user'),
						'href' => array ('update','id' => $this->_model->username)
					);
			}
			if(Yii::app()->user->checkAccess('Users.canChangePwd'))
			{
				$all['changePwd'] = array(
						'icon' => Yii::app()->request->baseUrl . '/images/lock.png',
						'label' => Yii::t('submenu', 'Change password'),
						'href' => array ('changePwd','id' => $this->_model->username)
					);
			}
			if(Yii::app()->user->checkAccess('Users.canDelete'))
			{
				$all['delete'] = array(
						'icon' => Yii::app()->request->baseUrl . '/images/del.png',
						'label' => Yii::t('submenu', 'Delete user'),
						'link' => array (
							'submit' => array ('delete','id' => $this->_model->username),
							'confirm' => Yii::t('submenu', 'Are you sure?')
						)
					);
			}
		}
		
		return $all;
		
		//return $submenu;
	}

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction = 'list';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array (// perform access control for CRUD operations
			'accessControl'
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array (
			array(
				'allow', 
				'actions' => array(
					'admin', 'show'
				),
				'roles' => array('Users.canList')
			),
			array(
				'allow', 
				'actions' => array(
					'update'
				),
				'roles' => array('Users.canUpdate')
			),
			array(
				'allow', 
				'actions' => array(
					'create'
				),
				'roles' => array('Users.canCreate')
			),
			array(
				'allow', 
				'actions' => array(
					'changePwd'
				),
				'roles' => array('Users.canChangePwd')
			),
			array(
				'allow', 
				'actions' => array(
					'delete'
				),
				'roles' => array('Users.canDelete')
			),
			array (
				'deny', // deny all users
				'users' => array (
					'*'
				)
			)
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow() {
		$this->render('show', array (
			'model' => $this->loaduser()
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate() {
		$model = new UserForm(true);

		if (!isset ($_POST['UserForm']) && !isset ($_POST['AdviserForm'])) {
			$this->render('create', array (
				'model' => $model
			));
		} else {
			$arr = null;
			if (isset ($_POST['UserForm'])) {
				$arr = $_POST['UserForm'];
			}

			if ($arr == null) {
				$this->render('create', array (
					'model' => $model
				));
			} else {
				$model = new UserForm();
				$model->scenario = UserForm::CREATE;

				if (isset ($arr['username'])) {
					$model->attributes = $arr;
					if (isset($_POST['UserForm']['roles']))
					{
						$model->setRoles($_POST['UserForm']['roles']);
					}else{
						$model->setRoles(array());
					}
					$model->validate();
					if (!$model->hasErrors() && $model->save()) {
						$this->redirect(array (
							'show',
							'id' => $model->username
						));
					} else {
						$this->render('create', array (
							'model' => $model
						));
					}
				} else {
					$this->render('create', array (
						'model' => $model
					));
				}
			}
		}
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate() {
		$user = $this->loaduser();
		$model = new UserForm(false);
		$model->attributes = $user->attributes;

		$model->scenario = UserForm::UPDATE;
		
		$arr = null;

		if (isset ($_POST['UserForm']))
			$arr = $_POST['UserForm'];

		if ($arr == null) {
			$this->render('update', array (
				'model' => $model
			));
		} else {
			$model->attributes = $arr;
					if (isset($_POST['UserForm']['roles']))
					{
						$model->setRoles($_POST['UserForm']['roles']);
					}else{
						$model->setRoles(array());
					}
			$model->validate();
			if (!$model->hasErrors()) {
				$this->redirect(array (
					'show',
					'id' => $model->username
				));
			} else {
				$this->render('update', array (
					'model' => $model
				));
			}
		}
	}

	public function actionChangePwd() {
		$user = $this->loaduser();
		$model = new UserForm(false);
		$model->attributes = $user->attributes;
		$model->getRoles();
		$model->scenario = UserForm::CHANGE_PASSWORD;
		$arr = null;

		if (isset ($_POST['UserForm']))
			$arr = $_POST['UserForm'];

		if ($arr == null) {
			$model->password = "";
			$this->render('changePwd', array (
				'model' => $model
			));
		} else {
			$model->attributes = $arr;
			$model->validate();
			if ($model->password == "")
				$model->addError('password', Yii::t('user', 'Password cannot be empty'));
			if (!$model->hasErrors())
				$this->redirect(array (
					'show',
					'id' => $model->username
				));
			else
				$this->render('changePwd', array (
					'model' => $model
				));
		}
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete() {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loaduser()->delete();
			$this->redirect(array (
				'list'
			));
		} else
			throw new CHttpException(400, Yii::t('user', 'Invalid request. Please do not repeat this request again.'));
	}

	/**
	 * Lists all models.
	 */
	public function actionList() {
		$criteria = new CDbCriteria;

		$pages = new CPagination(user::model()->count($criteria));
		$pages->pageSize = self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$models = user::model()->findAll($criteria);

		$this->render('list', array (
			'models' => $models,
			'pages' => $pages
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$this->processAdminCommand();

		$criteria = new CDbCriteria;

		$pages = new CPagination(user::model()->count($criteria));
		$pages->pageSize = self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$sort = new CSort('user');
		$sort->applyOrder($criteria);

		$models = user::model()->findAll($criteria);

		$this->render('admin', array (
			'models' => $models,
			'pages' => $pages,
			'sort' => $sort
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loaduser($id = null) {
		if ($this->_model === null) {
			if ($id !== null || isset ($_GET['id']))
				$this->_model = user::model()->findbyPk($id !== null ? $id : $_GET['id']);
			if ($this->_model === null)
				throw new CHttpException(404, Yii::t('user', 'The requested page does not exist.<br />No user with id {id} found.', array (
					'{id}' => $_GET['id']
				)));
		}
		return $this->_model;
	}

	/**
	 * Executes any command triggered on the admin page.
	 */
	protected function processAdminCommand() {
		if (isset ($_POST['command'], $_POST['id']) && $_POST['command'] === 'delete') {
			$this->loaduser($_POST['id'])->delete();
			// reload the current page to avoid duplicated delete actions
			$this->refresh();
		}
	}
}
?>
